package com.horizon.zk;

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.utils.CloseableUtils;

import lombok.Data;
import lombok.extern.slf4j.Slf4j;

/**
 * @author Administrator
 * @date 2021/8/29
 */
@Slf4j
@Data
public class CuratorZKClient {
    private CuratorFramework client;

    // zk集群地址
    private static final String ZK_ADDRESS = "127.0.0.1:2181";

    private String zkAddress = "127.0.0.1:2181";
    // 内部类初始化对象
    private static class SingletonInstanceHandler {
        public static CuratorZKClient instance = new CuratorZKClient();
    }

    public static CuratorZKClient getInstance() {
        CuratorZKClient instance = SingletonInstanceHandler.instance;
        // 初始化客户端
        instance.init();
        return instance;
    }

    public CuratorZKClient()
    {
    }
    public CuratorZKClient(String zkConnect)
    {
        this.zkAddress = zkConnect;
        init();
    }
    public void init() {
        if (null != client) {
            return;
        }

        // 创建客户端
        client = ClientFactory.createSimple(ZK_ADDRESS);
        // 启动客户端实例， 连接服务器
        client.start();
    }

    public void destroy() {
        CloseableUtils.closeQuietly(client);
    }

}
